import { ref } from 'vue';
import { CaptchaVO, LoginParam } from '/@/api/auth/login/types';
import { getCaptcha, login } from '/@/api/auth/login';
import { FormRules } from 'tdesign-vue-next';
import { LoginTypeEnum } from '/@/views/login/types';
import { useUserStore } from '/@/store/modules/user';
import { useRouter } from 'vue-router';

const loginFormRules: FormRules<LoginParam> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { max: 32, message: '用户名长度不能超过32', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { max: 32, message: '密码长度不能超过32', trigger: 'blur' },
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
};
/**
 * 使用登录
 */
const useLogin = () => {
  const router = useRouter();
  //登录表单
  const loginForm = ref<LoginParam>({
    username: '',
    password: '',
    uuid: '',
    code: '',
    loginType: LoginTypeEnum.PASSWORD,
  });
  // 验证码图片
  const imageSrc = ref<string>('');
  // form表单dom
  const formRef = ref();
  //登录loading变量
  const loginLoading = ref(false);
  /**
   * 初始化验证码
   */
  const initCaptchaVO = async () => {
    const res = (await getCaptcha()) as CaptchaVO;
    loginForm.value.uuid = res.key!;
    imageSrc.value = res.captchaImage!;
  };
  /**
   * 切换登录类型
   * @param loginType
   */
  const cutLoginType = (loginType: LoginTypeEnum) => {
    loginForm.value.loginType = loginType;
  };
  /**
   * 登录
   */
  const loginHandle = async () => {
    const resValidate = await formRef.value.validate();
    if (typeof resValidate !== 'boolean') {
      return;
    }
    loginLoading.value = true;
    const res = await login(loginForm.value, {
      callBack: () => (loginLoading.value = false),
    });
    const user = useUserStore();
    user.username = res.username!;
    user.orgId = res.orgId!;
    user.comId = res.comId!;
    user.realName = res.realName!;
    user.userId = res.userId!;
    await router.push({
      path: '/',
    });
  };
  return {
    loginForm,
    imageSrc,
    initCaptchaVO,
    formRef,
    loginHandle,
    loginLoading,
    cutLoginType,
  };
};
export { loginFormRules, useLogin };
